<?php
	if(isset($_POST['submit'])) {
	    require_once 'model/database.php';
	    $connect = connectDB();
	    $email = mysqli_real_escape_string($connect,$_POST['email']);
	    $passwd = mysqli_real_escape_string($connect,$_POST['password']);
	    $hash_pw = sha1($passwd);

	    $query =    "SELECT id, name
	                FROM members
	                WHERE email='$email'
	                AND passwd='$hash_pw'
	                LIMIT 1";
	    $result = mysqli_query($connect, $query) or die(mysqli_error($connect));
	    if(mysqli_num_rows($result) == 1) {
	        while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
	            $_SESSION['id'] = $rows['id'];
	            $_SESSION['email'] = $email;
	            if (isset($_POST['remember'])) {
	            	setcookie("id", $_SESSION['id'], time()+ 7*24*60*60);
	            	setcookie("email", $email, time()+ 7*24*60*60);
	            }
	            $msg = 'isLogin';
	        }
	    } else {
	    	$msg = 'isFault';
	    }
	    mysql_free_result($result);
	} else {
		if(isset($_SESSION['id'])){
			$msg = 'isLogin';
		} else if (isset($_COOKIE['id'])) {
			$_SESSION['id'] = $_COOKIE['id'];
			$_SESSION['email'] = $_COOKIE['email'];
			$msg = 'isLogin';
		} else {
			$msg = 'isLogout';
		}
	}
?>
<div id="header-wrapper">
	<div id="header">
		<div id="logo">
			<a href="index.php">UET-VNU</a>
		</div>
		<div id="menu">
            <div id="loginBox">
                <form id="loginForm" action="" method="post" name="login">
                    <fieldset id="body">
                        <fieldset>
                            <label for="email">Email Address</label>
                            <input type="text" name="email" id="email" />
                        </fieldset>
                        <fieldset>
                            <label for="password">Password</label>
                            <input type="password" name="password" id="password" />
                        </fieldset>
                        <input type="submit" id="login" value="Sign in" name="submit"/>
                        <label for="checkbox"><input type="checkbox" id="checkbox" name="remember"/>Remember me</label>
                    </fieldset>
                    <div id="link">
	                    <a href="register.php">Create new account</a>
	                    <a href="#">Forgot your password?</a>
                	</div>
                </form>
            </div>
			<a href="index.php" class="amenu">Home</a>
			<a href="explorer.php" class="amenu">My Photo</a>
			<a href="editor.php" class="amenu">Editor</a>
			<a href="#" class="amenu">About</a>
<?php
	if($msg == "isLogin"){
		echo "<a href='logout.php' id='logoutButton' class='amenu'>Logout</a>\n";
	} elseif ($msg == 'isLogout') {
	 	echo "<a href='#'' id='loginButton' class='amenu'><span>Login</span></a>\n";
	} else {
		echo "<a href='#'' id='loginButton' class='amenu'><span>Login</span></a>\n";
	}
?>
		</div>
	</div>
</div>
